<?php

    /**
     *      [Discuz!] (C)2001-2099 Comsenz Inc.
     *      This is NOT a freeware, use is subject to license terms
     *      $Id: forumindex.php 27451 2012-02-01 05:48:47Z monkey $
     *      提交文章评论
     */
    if (!defined('IN_MOBILE_API')) {
        exit('Access Denied');
    }

    include_once 'forum.php';

    class cloud_api {

        function common() {

        }

        function output() {
            if (empty($_GET['appid'])) {
                //正常返回
                $variable = array(
                    'code' => 1001,
                    'messagestr' => '缺少参数：appid!',
                );
                cloud_core::result(cloud_core::variable($variable));
            }

            //获取推送条件
            $where = ' where caid='.$_GET['appid'];
            if(!empty($_GET['push_province'])){
                $where .= ' and province="'.$_GET[push_province].'"';
            }
            if(!empty($_GET['push_city'])){
                $where .= ' and city="'.$_GET['push_city'].'"';
            }
            if(!empty($_GET['push_operator'])){
                $where .= ' and operator="'.$_GET['push_operator'].'"';
            }
            if(!empty($_GET['push_versions'])){
                $where .= ' and versions="'.$_GET['push_versions'].'"';
            }
            if(!empty($_GET['push_platform'])){
                if($_GET['push_platform'] == 'ios'){
                    $data = C::t('#cloud#cloud_ios_push')->get_ios_by_where($where);
                }
                if($_GET['push_platform'] == 'android'){
                    $data = C::t('#cloud#cloud_android_push')->get_android_by_where($where);
                }
            }else{
                $data = C::t('#cloud#cloud_ios_push')->fetch_all_by_caid($where);
            }



            echo "<pre>";
            print_r($data);exit;
            $count = empty($_GET['count']) ? 0 : $_GET['count'];
            //ios push
            if (!empty($data)) {
                foreach ($data as $key => $val) {
                    $token = $val['token'];
                    $dev = $val['dev'];
                    self::push_ios_message($token, $count, $dev, $_GET['appid']);
                }
            }


            //android push
            $msg_content = array('n_title' => '通知', 'n_content' => '内容');
            $str = self::push_android_message($appkeys = '', $masterSecret = '', $sendno = 1, $receiver_type = 4, $receiver_value = '', $msg_type = 1, $msg_content, $platform = 'android');

            //正常返回
            $variable = array(
                'messagestr' => $str,
            );
            cloud_core::result(cloud_core::variable($variable));
        }

        //ios push function
        function push_ios_message($token, $count, $dev, $caid) {
            // 得到deviceToken
            $deviceToken = $token;
            // 密钥:
            $passphrase = 'youdao';
            // 要推送的消息:
            $sound = 'default';
            $message = empty($_GET['message']) ? '测试推送数据接口' : $_GET['message'];

            $ctx = stream_context_create();
            if ($dev == 0) {
                //                echo 'aaaaa0:'.$dev.'<br>';
                stream_context_set_option($ctx, 'ssl', 'local_cert', 'source/plugin/cloud/pushPem/product/' . $caid . '.pem');
                stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
                // 打开一个连接到apns服务器
                $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
            } else {
                //                echo 'aaaaa1:'.$dev.'<br>';
                stream_context_set_option($ctx, 'ssl', 'local_cert', 'source/plugin/cloud/pushPem/develop/' . $caid . '.pem');
                stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
                // 打开一个连接到apns服务器
                $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
            }

            //             if (!$fp)
            //               exit("Failed to connect: <br>$err<br>$errstr<br>" . PHP_EOL);

            $body['aps'] = array(
                'alert' => $message,
                'sound' => $sound,
                "badge" => $count
            );
            // 转换json
            $payload = json_encode($body);
            $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
            $result = fwrite($fp, $msg, strlen($msg));
            //            echo '$result:'.$result.'<br>';
            return $result ? true : false;
            fclose($fp);
        }

        //android push function
        function push_android_message($appkeys, $masterSecret, $sendno = 1, $receiver_type = 4, $receiver_value = array(), $msg_type = 1, $msg_content = array(), $platform = 'android') {

            //        $msg_content =array('n_title'=>'通知','n_content'=>'内容');
            //        $content = json_encode($msg_content,true);
            //        $receiver_value =array(1,2,3);
            //        $receiver_value = implode(',',$receiver_value);
            $url = 'http://api.jpush.cn:8800/sendmsg/v2/sendmsg';
            $param = '';
            $param .= '&sendno=' . $sendno;
            $appkeys = empty($appkeys) ? '217f48a6776317af7ac9c517' : $appkeys;
            $param .= '&app_key=' . $appkeys;
            $param .= '&receiver_type=' . $receiver_type;
            if ($receiver_type == 3 && !empty($receiver_value)) {
                $receiver_value = implode(',', $receiver_value);
                $param .= '&receiver_value=' . $receiver_value;
            }
            $masterSecret = empty($masterSecret) ? 'cc64be722d75809a70be204e' : $masterSecret;
            $verification_code = md5($sendno . $receiver_type . $receiver_value . $masterSecret);
            $param .= '&verification_code=' . $verification_code;
            $param .= '&msg_type=' . $msg_type;
            $param .= '&msg_content=' . json_encode($msg_content, true);
            $param .= '&platform=' . $platform;
            $res = self::request_post($url, $param);
            if ($res === false) {
                return false;
            }
            $res_arr = json_decode($res, true);
            $res_arr['errmsg'] = "没有错误信息";
            switch (intval($res_arr['errcode'])) {
                case 0:
                    $res_arr['errmsg'] = '发送成功';
                    //echo '发送成功';
                    break;
                case 10:
                    $res_arr['errmsg'] = '系统内部错误';
                    //echo '系统内部错误';
                    break;
                case 1001:
                    $res_arr['errmsg'] = '只支持 HTTP Post 方法，不支持 Get 方法';
                    //echo '只支持 HTTP Post 方法，不支持 Get 方法';
                    break;
                case 1002:
                    $res_arr['errmsg'] = '缺少了必须的参数';
                    //echo '缺少了必须的参数';
                    break;
                case 1003:
                    $res_arr['errmsg'] = '参数值不合法';
                    //echo '参数值不合法';
                    break;
                case 1004:
                    $res_arr['errmsg'] = '验证失败';
                    //echo '验证失败';
                    break;
                case 1005:
                    $res_arr['errmsg'] = '消息体太大';
                    //echo '消息体太大';
                    break;
                case 1007:
                    $res_arr['errmsg'] = 'receiver_value 参数 非法';
                    //echo 'receiver_value 参数 非法';
                    break;
                case 1008:
                    $res_arr['errmsg'] = 'appkey参数非法';
                    //echo 'appkey参数非法';
                    break;
                case 1010:
                    $res_arr['errmsg'] = 'msg_content 不合法';
                    //echo 'msg_content 不合法';
                    break;
                case 1011:
                    $res_arr['errmsg'] = '没有满足条件的推送目标';
                    //echo '没有满足条件的推送目标';
                    break;
                case 1012:
                    $res_arr['errmsg'] = 'iOS 不支持推送自定义消息。只有 Android 支持推送自定义消息';
                    //echo 'iOS 不支持推送自定义消息。只有 Android 支持推送自定义消息。';
                    break;
                default:
                    //echo '调用成功';
                    break;
            }
            $str = "第" . $res_arr['sendno'] . "条发送" . $res_arr['errmsg'] . "！";
            return $str;
        }

        function request_post($url = '', $param = '') {
            if (empty($url) || empty($param)) {
                return false;
            }
            $postUrl = $url;
            $curlPost = $param;
            $ch = curl_init(); //初始化curl
            curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
            curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
            //echo $url;echo $curlPost;exit;
            $data = curl_exec($ch); //运行curl
            curl_close($ch);
            return $data;
        }
    }

?>